﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.IO;
using System.Threading;
using FtpLibrary;
using System.Text.RegularExpressions;
using FileBrowser;


namespace FtpUpload
{

    public partial class FrmMain : Form
    {
        delegate void SetTextCallback(int text);

        public struct SHFILEINFO
        {
            public IntPtr hIcon;
            public int iIcon;
            public uint dwAttributes;
            public char szDisplayName;
            public char szTypeName;
            public const uint SHGFI_ICON = 0x100;
            public const uint SHGFI_LARGEICON = 0x0; //大图标 32×32
            public const uint SHGFI_SMALLICON = 0x1; //小图标 16×16
            public const uint SHGFI_USEFILEATTRIBUTES = 0x10;

            [DllImport("User32.dll", EntryPoint = "DestroyIcon")]
            public static extern int DestroyIcon(IntPtr hIcon);

            [DllImport("Shell32.dll", EntryPoint = "SHGetFileInfo", SetLastError = true, CharSet = CharSet.Auto)]
            public static extern IntPtr SHGetFileInfo(string pszPath, uint dwFileAttributes, ref SHFILEINFO psfi, uint cbFileInfo, uint uFlags);



        }

        private string m_ftp_server = "61.150.91.98";
        private int m_ftp_port = 2021;
        private string m_user_name = "medal";
        private string m_password = "2004111091";
        private long m_user_id = 100;

        //是否正在上传
        private bool m_is_uploading = false;

        //文件总大小
        private long m_file_size = -1;
        //目前正上传的大小
        private long m_cur_upload_size = 0;
        //是否暂停过
        private string m_is_stoped = "0";

        //上次上传的大小
        private long m_uploaded_size = 0;

        /// <summary>
        /// 可以上传的文件名后缀
        /// </summary>
        string[] m_upload_file_ext;
        string m_upload_file_string;

        //排队上传的文件队列
        Queue<string> m_upload_queue = new Queue<string>();

        //是否已经登录
        bool m_is_login = false;

        /// <summary>
        /// 当前上传的文件名
        /// </summary>
        private string m_cur_upload_file_name = string.Empty;

        Ftp m_ftp;



        [DllImport("Shell32.dll")]
        public static extern int ExtractIcon(IntPtr h, string strx, int ii);

        [DllImport("Shell32.dll")]
        public static extern int SHGetFileInfo(string pszPath, uint dwFileAttributes, ref SHFILEINFO psfi, uint cbFileInfo, uint uFlags);


        private Icon GetIcon(string fileName, bool isLargeIcon)
        {
            SHFILEINFO shfi = new SHFILEINFO();
            IntPtr hI;

            if (isLargeIcon)
                hI = SHFILEINFO.SHGetFileInfo(fileName, 0, ref shfi, (uint)Marshal.SizeOf(shfi), SHFILEINFO.SHGFI_ICON | SHFILEINFO.SHGFI_USEFILEATTRIBUTES | SHFILEINFO.SHGFI_LARGEICON);
            else
                hI = SHFILEINFO.SHGetFileInfo(fileName, 0, ref shfi, (uint)Marshal.SizeOf(shfi), SHFILEINFO.SHGFI_ICON | SHFILEINFO.SHGFI_USEFILEATTRIBUTES | SHFILEINFO.SHGFI_SMALLICON);

            Icon icon = Icon.FromHandle(shfi.hIcon).Clone() as Icon;

            SHFILEINFO.DestroyIcon(shfi.hIcon); //释放资源
            return icon;
        }


        public FrmMain()
        {
            InitializeComponent();

            Control.CheckForIllegalCrossThreadCalls = false;
            Icon t_ic0 = GetExtractIcon("%SystemRoot%\\system32\\shell32.dll", 15);

            img_tree.Images.Add(t_ic0);
            Icon t_ic1 = GetExtractIcon("%SystemRoot%\\system32\\shell32.dll", 5);
            img_tree.Images.Add(t_ic1);
            Icon t_ic2 = GetExtractIcon("%SystemRoot%\\system32\\shell32.dll", 7);
            img_tree.Images.Add(t_ic2);
            Icon t_ic3 = GetExtractIcon("%SystemRoot%\\system32\\shell32.dll", 11);
            img_tree.Images.Add(t_ic3);
            Icon t_ic4 = GetExtractIcon("%SystemRoot%\\system32\\shell32.dll", 3);
            img_tree.Images.Add(t_ic4);
            Icon t_ic5 = GetExtractIcon("%SystemRoot%\\system32\\shell32.dll", 4);
            img_tree.Images.Add(t_ic5);
            Icon t_ic6 = GetExtractIcon("%SystemRoot%\\system32\\shell32.dll", 101);
            img_tree.Images.Add(t_ic6);
            Icon t_ic7 = GetExtractIcon("%SystemRoot%\\system32\\shell32.dll", 9);
            img_tree.Images.Add(t_ic7);


            bv_file.SelectUploadListHandler += new SelectUploadListEventHandler(GetUploadFile);
           
        }

        /// <summary>
        /// 选择上传的文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GetUploadFile(object sender, SelectUploadListEventArgs e)
        {
            if (m_is_login == false)
            {
                MessageBox.Show("请先登录!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            StringBuilder t_sb = new StringBuilder();
            if (e.FileList != null && e.FileList.Count > 0)
            {
                foreach (string t_file in e.FileList)
                {
                    AddUploadFileToList(t_file, "0", GetUploadedSize(t_file));
                }
                
            }

            if (m_is_uploading == false)
            {
                DoUploadFile();
            }
        }

        /// <summary>
        /// 设置ftp
        /// </summary>
        private void SetFtp()
        {
            m_ftp = new Ftp();
            m_ftp.Passive = true;
            m_ftp.Timeout = 30000;


            m_ftp.CommandSent += new FtpCommandSentEventHandler(ftp_CommandSent);
            m_ftp.ResponseRead += new FtpResponseReadEventHandler(ftp_ResponseRead);
            m_ftp.StateChanged += new FtpStateChangedEventHandler(ftp_StateChanged);
            m_ftp.TransferProgress += new FtpTransferProgressEventHandler(ftp_TransferProgress);
            try
            {
                IAsyncResult ar = m_ftp.BeginConnect(m_ftp_server, m_ftp_port, null, null);
                while (!ar.IsCompleted)
                {
                    Application.DoEvents();
                    System.Threading.Thread.Sleep(1);
                }
                m_ftp.EndConnect(ar);

                m_ftp.Login(m_user_name, m_password);
            }
            catch (Exception ex)
            {
                WriteToLog(ex.Message, Color.Red);
            }
        }

        /// <summary>
        /// 发送命令回调
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void ftp_CommandSent(object sender, FtpCommandSentEventArgs e)
        {
            try
            {
                if (!IsDisposed)
                    Invoke(new FtpCommandSentEventHandler(CommandSent), new object[] { sender, e });
            }
            catch (Exception ex)
            {
                WriteToLog(ex.Message, Color.Red);
                GetRemoteFiles();
            }
        }

        /// <summary>
        /// 发送命令回调
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void CommandSent(object sender, FtpCommandSentEventArgs e)
        {
            const string PASS = "PASS";
            string command = e.Command.ToString();
            if (command != null && command.Length > PASS.Length && command.IndexOf(PASS) == 0)
            {
                command = "PASS ***";
            }
            WriteToLog(command, Color.DarkGreen);
        }

        /// <summary>
        /// 返回消息回调
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void ftp_ResponseRead(object sender, FtpResponseReadEventArgs e)
        {
            try
            {
                if (!IsDisposed)
                    Invoke(new FtpResponseReadEventHandler(ResponseRead), new object[] { sender, e });
            }
            catch (Exception ex)
            {
                WriteToLog(ex.Message, Color.Red);
                GetRemoteFiles();
            }
        }

        /// <summary>
        /// 返回消息回调
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void ResponseRead(object sender, FtpResponseReadEventArgs e)
        {
            WriteToLog(e.Response, Color.Blue);
        }


        /// <summary>
        /// 连接状态回调
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void ftp_StateChanged(object sender, FtpStateChangedEventArgs e)
        {
            try
            {
                if (!IsDisposed)
                    Invoke(new FtpStateChangedEventHandler(StateChanged), new object[] { sender, e });
            }
            catch (Exception ex)
            {
                WriteToLog(ex.Message, Color.Red);
                GetRemoteFiles();
            }
        }
        /// <summary>
        /// 连接状态回调
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void StateChanged(object sender, FtpStateChangedEventArgs e)
        {
            switch (e.NewState)
            {
                case FtpState.Disconnected:
                    break;
                case FtpState.Disposed:
                    break;
                case FtpState.Ready:
                    break;
            }
        }

        /// <summary>
        /// 传输过程回调
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void ftp_TransferProgress(object sender, FtpTransferProgressEventArgs e)
        {
            try
            {
                if (!IsDisposed)
                    Invoke(new FtpTransferProgressEventHandler(TransferProgress), new object[] { sender, e });
            }
            catch (Exception ex)
            {
                WriteToLog(ex.Message, Color.Red);
                GetRemoteFiles();
            }
        }

        /// <summary>
        /// 传输过程回调
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void TransferProgress(object sender, FtpTransferProgressEventArgs e)
        {

            if (e.State != FtpTransferState.None && m_file_size > 0)
            {
                m_cur_upload_size = e.BytesTransferred;

                decimal index = (decimal)(e.BytesTransferred+m_uploaded_size) / (decimal)m_file_size;

                index = index * 100;

                if (index > 100)
                    index = 100;

                SetProcess((int)index);
                
            }
        }

        private void SetText(int i_index)
        {

            if (this.rtb_remote_info.InvokeRequired)
            {
                SetTextCallback d = new SetTextCallback(SetText);
                this.Invoke(d, new object[] { i_index });
            }
            else
            {
                lock (rtb_remote_info)
                {
                    rtb_remote_info.Focus();
                    rtb_remote_info.SelectionColor = Color.Green;
                    rtb_remote_info.AppendText(string.Format("完成：{0}",i_index.ToString()) + "\r\n");
                }
               
            }
        }

       
        private void SetProcess(int i_upload_size)
        {

            tls_process.Value = i_upload_size;
            tls_info.Text = string.Format("完成：{0}%", (i_upload_size).ToString(".00"));
       
        }

        /// <summary>
        /// 记录消息
        /// </summary>
        /// <param name="message"></param>
        /// <param name="color"></param>
        public void WriteToLog(string message, Color color)
        {
            try
            {
                lock (rtb_remote_info)
                {
                    rtb_remote_info.Focus();
                    rtb_remote_info.SelectionColor = color;
                    rtb_remote_info.AppendText(message + "\r\n");
                }
            }
            catch { }
        }

        /// <summary>
        /// 窗体加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FrmMain_Load(object sender, EventArgs e)
        {
            SetFtpInfo();
            
        }

        /// <summary>
        /// 设置ftp信息 string.Format("{0}${1}${2}${3}", t_ftp_server, t_ftp_port, t_user_name, t_password);
        /// </summary>
        private void SetFtpInfo()
        {
            com._114sucai.ftp.Service1 t_ftp_info = new FtpUpload.com._114sucai.ftp.Service1();

            try
            {
                string t_ftp_con_info = t_ftp_info.GetFTPConnectionInfo();

                if (!string.IsNullOrEmpty(t_ftp_con_info))
                {
                    string[] t_ftp_arr = t_ftp_con_info.Split(new char[] { '$' }, StringSplitOptions.RemoveEmptyEntries);

                    if (t_ftp_arr != null && t_ftp_arr.Length == 4)
                    {
                        m_ftp_server = t_ftp_arr[0];
                        m_ftp_port = Convert.ToInt32(t_ftp_arr[1].ToString());
                        m_user_name = t_ftp_arr[2];
                        m_password = t_ftp_arr[3];
                    }
                }

                //允许上传的文件名后缀
                 m_upload_file_string = t_ftp_info.GetFileFormat();
                 if (!string.IsNullOrEmpty(m_upload_file_string))
                {
                    m_upload_file_ext = m_upload_file_string.Split(new char[] { '$' }, StringSplitOptions.RemoveEmptyEntries);
                }
            }
            catch (Exception ex)
            {
                WriteToLog(ex.ToString(), Color.Red);
            }
        }



        /// <summary>
        /// 连接上服务器
        /// </summary>
        private void ConnectHost()
        {
            try
            {
                GetUserRemoteFiles();

                List<UnUploadFileInfo> t_file_list = LocationManager.GetUnloadFile();

                if (t_file_list != null && t_file_list.Count > 0)
                {
                    foreach (UnUploadFileInfo t_file in t_file_list)
                    {
                        AddUploadFileToList(t_file.FileName, "1", t_file.UploadSize);
                    }
                }

            }
            catch 
            {
                GetUserRemoteFiles();
            }

           
        }

        /// <summary>
        /// 获取用户上传的文件列表
        /// </summary>
        /// <param name="list"></param>
        private void GetUserRemoteFiles()
        {
           
            try
            {
                FtpList t_remote_list = m_ftp.GetList();
                bool t_is_exists_user_dir = false;
                if (t_remote_list != null && t_remote_list.Count > 0)
                {
                    for (int index = 0; index < t_remote_list.Count; index++)
                    {
                        //是文件夹
                        if ((t_remote_list[index].IsSymlink && IsDirectory(t_remote_list[index].SymlinkPath)) || t_remote_list[index].IsDirectory)
                        {
                            if (t_remote_list[index].Name==m_user_id.ToString())
                            {

                                t_is_exists_user_dir = true;
                                break;
                            }

                        }
                    }
                }

                if (t_is_exists_user_dir == false)
                {
                    m_ftp.CreateDirectory(m_user_id.ToString());
                }
                
                m_ftp.ChangeDirectory(m_user_id.ToString());

                GetRemoteFiles();

              
            }
            catch (Exception ex)
            {
                WriteToLog(ex.Message, Color.Red);
            }
        }

        /// <summary>
        /// 获取文件列表
        /// </summary>
        /// <param name="list"></param>
        private void GetRemoteFiles()
        {
            try
            {
                FtpList t_remote_list = m_ftp.GetList();

                if (t_remote_list != null && t_remote_list.Count > 0)
                {
                    for (int index = 0; index < t_remote_list.Count; index++)
                    {
                        if (t_remote_list[index].Name == m_user_id.ToString())
                        {
                            m_ftp.ChangeDirectory(m_user_id.ToString());
                            t_remote_list = m_ftp.GetList();
                            break;
                        }
                    }

                    img_remote_file_icon.Images.Clear();


                    lst_remote_file.View = View.Details;
                    lst_remote_file.SmallImageList = img_remote_file_icon;

                    lst_remote_file.Clear();
                    lst_remote_file.Columns.Add("文件名", 160, HorizontalAlignment.Left);
                    lst_remote_file.Columns.Add("文件大小", 120, HorizontalAlignment.Left);
                    lst_remote_file.Columns.Add("访问时间", 200, HorizontalAlignment.Left);
                    string[] t_item_arr = new string[4];

                    int t_total_count = 0;


                    for (int index = 0; index < t_remote_list.Count; index++)
                    {

                        t_item_arr[0] = t_remote_list[index].Name;
                        t_item_arr[1] = t_remote_list[index].Size.ToString();
                        t_item_arr[2] = t_remote_list[index].Modified.ToString();


                        //得到每个文件的图标
                        string t_file_name = t_item_arr[0];
                        string t_file_ext = string.Empty;
                        int t_index = t_file_name.IndexOf(".");
                        if (t_index > -1)
                        {
                            t_file_ext = t_file_name.Substring(t_index);
                        }
                        try
                        {
                            SetIcon(img_remote_file_icon, t_file_ext, false);

                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message, "错误提示", 0, MessageBoxIcon.Error);
                        }

                        //插入列表项    
                        ListViewItem t_item = new ListViewItem(t_item_arr, img_remote_file_icon.Images.Count - 1);
                        lst_remote_file.Items.Insert(t_total_count, t_item);
                    }
                }

                //如果是上传中重新连接的
                if (m_is_uploading)
                {
                    DoUploadFile();
                }

                tlsm_upload.Enabled = true;
                tlsm_file_upload.Enabled = true;
                tls_reflash.Enabled = true;
                t_smi_reflash.Enabled = true;
                tlsm_stop_upload.Enabled = true;
                tlsm_queue_delete.Enabled = true;
            }
            catch (Exception ex)
            {
                WriteToLog(ex.Message, Color.Red);
            }

        }


        /// <summary>
        /// 是否是文件
        /// </summary>
        /// <param name="i_file_name"></param>
        /// <returns></returns>
        private static bool IsFile(string i_file_name)
        {
            i_file_name = GetFilenameFromPath(i_file_name);
            Regex t_reg = new Regex(@"(.*\..*)");
            Match t_match = t_reg.Match(i_file_name);
            return t_match.Success;
        }

        /// <summary>
        /// 是否是目录
        /// </summary>
        /// <param name="i_file_name"></param>
        /// <returns></returns>
        private static bool IsDirectory(string i_file_name)
        {
            return (!IsFile(i_file_name));
        }


        /// <summary>
        /// 获取文件名
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        private static string GetFilenameFromPath(string path)
        {
            int idx = path.LastIndexOf("\\");

            if (idx != -1 && idx + 1 != path.Length)
            {
                path = path.Substring(idx + 1);
            }

            return path;
        }

        /// <summary>
        /// 是否包含中文
        /// </summary>
        /// <param name="i_file_name"></param>
        /// <returns></returns>
        private bool IsContainCh(string i_file_name)
        {
            Regex t_reg = new Regex("[\u4e00-\u9fa5]");

            return t_reg.IsMatch(i_file_name);
 
        }


        /// <summary>
        /// 获取系统资源图标
        /// </summary>
        /// <param name="i_dll_name"></param>
        /// <param name="i_img_index"></param>
        /// <returns></returns>
        protected virtual Icon GetExtractIcon(string i_dll_name, int i_img_index)
        {
            try
            {
                IntPtr t_icon = (IntPtr)ExtractIcon(this.Handle, i_dll_name, i_img_index);
                if (!t_icon.Equals(null))
                {
                    Icon t_ret_icon = Icon.FromHandle(t_icon);
                    return t_ret_icon;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误提示", 0, MessageBoxIcon.Error);
            }
            return null;
        }

        /// <summary>
        /// 设置图标
        /// </summary>
        /// <param name="imageList"></param>
        /// <param name="FileName"></param>
        /// <param name="tf"></param>
        protected virtual void SetIcon(ImageList i_img_list, string i_file_name, bool i_is_big_icon)
        {
            //文件夹
            if (string.IsNullOrEmpty(i_file_name))
            {
                Icon t_ic0 = GetExtractIcon("%SystemRoot%\\system32\\shell32.dll", 3);
                i_img_list.Images.Add(t_ic0);
                return;
            }
            i_img_list.Images.Add(GetIcon(i_file_name, i_is_big_icon));

        }


        /// <summary>
        /// 上传操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tlsm_upload_Click(object sender, EventArgs e)
        {
            if (m_is_uploading == false)
            {
                DoUploadFile();
            }

        }

        /// <summary>
        /// 上传失败中的文件
        /// </summary>
        private void DoUploadCurFile()
        {
            if (!string.IsNullOrEmpty(m_cur_upload_file_name))
            {
               

                for (int index = 0; index < lst_result_info.Items.Count; index++)
                {
                    if (lst_result_info.Items[index].SubItems[0].Text.Trim() == m_cur_upload_file_name)
                    {
                        lst_result_info.Items[index].SubItems[5].Text = "上传中";
                        lst_result_info.Items[index].ForeColor = Color.Green;
                    }
                }
                UploadFile(m_cur_upload_file_name, GetFilenameFromPath(m_cur_upload_file_name), m_uploaded_size);
            }
        }

        /// <summary>
        /// 线程异步上传
        /// </summary>
        private void DoUploadFile()
        {
            DoUploadCurFile();

 
            m_is_uploading = true;

            string t_file_name=string.Empty;
            if (m_upload_queue.Count > 0)
            {
                t_file_name = m_upload_queue.Dequeue();
                if (string.IsNullOrEmpty(t_file_name))
                {
                    m_is_uploading = false;
                    return;
                }
            }
            else
            {
                m_is_uploading = false;
                return;
            }


            for (int index = 0; index < lst_result_info.Items.Count; index++)
            {
                if (lst_result_info.Items[index].SubItems[0].Text == t_file_name)
                {
                    lst_result_info.Items[index].SubItems[5].Text = "上传中";

                    lst_result_info.Items[index].ForeColor = Color.Green;

                    m_cur_upload_file_name = lst_result_info.Items[index].SubItems[0].Text;

                    if (!File.Exists(m_cur_upload_file_name))
                    {
                        lst_result_info.Items[index].SubItems[5].Text = "原始文件已经不存在";
                        lst_result_info.Items[index].ForeColor = Color.Red;
                        continue;

                    }

                    m_uploaded_size = GetUploadedSize(lst_result_info.Items[index].SubItems[1].Text);

                    UploadFile(lst_result_info.Items[index].SubItems[0].Text, lst_result_info.Items[index].SubItems[1].Text, m_uploaded_size);
                }
            }
              
            
        }

        private long GetUploadedSize(string i_file_name)
        {
            long t_upload_size = 0;
            for (int index = 0; index < lst_remote_file.Items.Count; index++)
            {
                if (lst_remote_file.Items[index].SubItems[0].Text == i_file_name)
                {
                    t_upload_size = Convert.ToInt64(lst_remote_file.Items[index].SubItems[1].Text.ToString());
                    break;
                }
            }
            return t_upload_size;
        }

       

        /// <summary>
        /// 添加上传文件到文件列表
        /// </summary>
        /// <param name="i_file_name"></param>
        private void AddUploadFileToList(string i_file_name, string i_is_stoped, long i_uploaded_size)
        {

            if (CheckIsExists(i_file_name, i_is_stoped))
                return;

            Monitor.Enter(m_upload_queue);
            m_upload_queue.Enqueue(i_file_name);
            Monitor.Exit(m_upload_queue);

            if (File.Exists(i_file_name))
            {
                m_file_size = (new FileInfo(i_file_name)).Length;
            }

            string[] t_str = new string[6];
            t_str[0] = i_file_name;
            t_str[1] = GetFilenameFromPath(i_file_name);
            t_str[2] = m_file_size.ToString();
            t_str[3] = i_is_stoped;
            t_str[4] = i_uploaded_size.ToString();
            t_str[5] = "排队";

            

            if (IsCanUploadFileExt(t_str[1]) == false)
            {
                MessageBox.Show(string.Format("目前只支持{0}后缀的文件上传!", m_upload_file_string.Replace("$", ","))+Environment.NewLine+string.Format("文件：【{0}】不合法",i_file_name), "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            if (IsContainCh(t_str[1]))
            {
                MessageBox.Show("上传的文件名不能包含中文!"+Environment.NewLine+string.Format("文件：【{0}】包含了中文",i_file_name), "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            ListViewItem t_item_queue = new ListViewItem(t_str, 1);

            lst_result_info.Items.Add(t_item_queue);   
          
        }

        /// <summary>
        /// 是否已在队列里
        /// </summary>
        /// <param name="i_file_name"></param>
        /// <returns></returns>
        private bool CheckIsExists(string i_file_name,string i_is_stoped)
        {
            if (IsFile(i_file_name) == false)
            {
                MessageBox.Show("不能上传目录，请选择文件上传!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return true;
            }

            bool t_is_exist = false;
            if (i_is_stoped == "1")
            {
                for (int index = 0; index < lst_remote_file.Items.Count; index++)
                {
                    if (lst_remote_file.Items[index].SubItems[0].Text == GetFilenameFromPath(i_file_name))
                    {
                        MessageBox.Show(string.Format("文件【{0}】已经上传过了,请重新命名上传!", GetFilenameFromPath(i_file_name)), "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        LocationManager.DelSetting(i_file_name);
                        t_is_exist = true;
                        break;
                    }
                }
            }
            if (t_is_exist)
                return t_is_exist;
            for (int index = 0; index < lst_result_info.Items.Count; index++)
            {
                if (lst_result_info.Items[index].SubItems[0].Text.Trim() == i_file_name)
                {
                    t_is_exist = true;
                    break;
                }
            }
            return t_is_exist;
        }


        /// <summary>
        /// 是否是可以上传文件后缀
        /// </summary>
        /// <param name="i_file_name"></param>
        /// <returns></returns>
        private bool IsCanUploadFileExt(string i_file_name)
        {
            if (m_upload_file_ext == null || m_upload_file_ext.Length <= 0)
                return true;

            if (string.IsNullOrEmpty(i_file_name))
                return false;

         
            string t_file_ext = string.Empty;
            int t_index = i_file_name.IndexOf(".");
            if (t_index > -1)
            {
                t_file_ext = i_file_name.Substring(t_index + 1);
            }

            if (string.IsNullOrEmpty(t_file_ext))
                return false;

            bool t_is_can_upload_file_ext = false;

            foreach (string t_ext in m_upload_file_ext)
            {
                if (t_ext.ToLower().Equals(t_file_ext))
                {
                    t_is_can_upload_file_ext = true;
                    break;
                }
            }

            return t_is_can_upload_file_ext;

        }

        /// <summary>
        /// ftp上传文件
        /// </summary>
        /// <param name="localFile"></param>
        /// <param name="remoteFile"></param>
        public void UploadFile(string i_local_file, string i_remote_file,long i_uploaded_size)
        {
            try
            {
                if (File.Exists(m_cur_upload_file_name))
                {
                    m_file_size = (new FileInfo(m_cur_upload_file_name)).Length;
                }

                m_ftp.TransferType = FtpTransferType.Ascii;
                if (i_uploaded_size == 0)
                {
                    m_ftp.BeginPutFile(i_local_file, i_remote_file, new AsyncCallback(UploadCallback), null);
                }
                else
                {
                    m_ftp.BeginAppendFile(i_local_file, i_remote_file,i_uploaded_size,-1, new AsyncCallback(AppendCallback), null);
                   // m_ftp.BeginPutFile(i_local_file, i_remote_file, i_uploaded_size,i_uploaded_size,-1,new AsyncCallback(UploadCallback), null);
                }
            }
            catch (Exception ex)
            {
                WriteToLog(ex.Message, Color.Red);
           
                GetRemoteFiles();

                if (m_is_uploading)
                {
                    DoUploadFile();
                }
            }
        }

        /// <summary>
        /// 传输文成委托
        /// </summary>
        /// <param name="i_error"></param>
        /// <param name="i_reflash_ftp"></param>
        private delegate void TransferFinishedDelegate(Exception i_error, bool i_reflash_ftp);


        /// <summary>
        /// 断点上传回调
        /// </summary>
        /// <param name="i_asyn_result"></param>
        public void AppendCallback(IAsyncResult i_asyn_result)
        {
            try
            {
                m_ftp.EndAppendFile(i_asyn_result);
                if (!IsDisposed)
                    Invoke(new TransferFinishedDelegate(TransferFinished), new object[] { null, true });
            }
            catch (Exception ex)
            {
                WriteToLog(ex.Message, Color.Red);
               
                GetRemoteFiles();


                if (m_is_uploading)
                {
                    DoUploadFile();
                }
            }
        }

        /// <summary>
        /// 上传回调
        /// </summary>
        /// <param name="i_asyn_result"></param>
        public void UploadCallback(IAsyncResult i_asyn_result)
        {
            try
            {
                m_ftp.EndPutFile(i_asyn_result);
                if (!IsDisposed)
                    Invoke(new TransferFinishedDelegate(TransferFinished), new object[] { null, true });
            }
            catch (Exception ex)
            {
                WriteToLog(ex.Message, Color.Red);
            
                GetRemoteFiles();

                if (m_is_uploading)
                {
                    DoUploadFile();
                }
            }
        }

        /// <summary>
        /// 传输完毕
        /// </summary>
        /// <param name="error"></param>
        /// <param name="refreshFtp"></param>
        private void TransferFinished(Exception i_error, bool i_reflash_ftp)
        {

            lst_remote_file.Enabled = true;

            SetProcess(100);

            //移除已经上传的文件
            foreach(ListViewItem t_item in lst_result_info.Items)
            {
                if (t_item.SubItems[0].Text == m_cur_upload_file_name)
                {
                    lst_result_info.Items.Remove(t_item);
                    break;
                }
            }

            m_file_size = -1;

            m_uploaded_size = 0;

            if (m_is_stoped == "1")
            {
                try
                {
                    LocationManager.DelSetting(m_cur_upload_file_name);
                }
                catch { }
            }


            m_cur_upload_size = 0;

           

            InsertDataToDB();

            m_cur_upload_file_name = string.Empty;

            tls_process.Value = 0;

            tls_info.Text = "空闲中";

            if (m_upload_queue.Count == 0)
            {
                GetRemoteFiles();
            }
            else
            {
                DoUploadFile();
            }

        }

        /// <summary>
        /// 用户登陆
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tlsm_login_Click(object sender, EventArgs e)
        {
            FrmLogin t_frm_login = new FrmLogin();
            DialogResult t_dlr = t_frm_login.ShowDialog();

            //登陆成功
            if (t_dlr == DialogResult.OK)
            {
                tls_reflash.Enabled = true;

                m_user_id = t_frm_login.m_user_id;

                SetFtp();

                ConnectHost();

                m_is_login = true;
            }
        }

        /// <summary>
        /// 上传成功，把数据写入数据库
        /// </summary>
        private void InsertDataToDB()
        {
            com._114sucai.ftp.Service1 t_frm_service = new com._114sucai.ftp.Service1();

            try
            {
                t_frm_service.InsertUserUploadData(m_user_id, GetFilenameFromPath( m_cur_upload_file_name), DateTime.Now);
                
            }
            catch (Exception ex)
            {
                WriteToLog(ex.ToString(), Color.Red);

                GetRemoteFiles();

                if (m_is_uploading)
                {
                    DoUploadFile();
                }
            }
        }

        /// <summary>
        /// 刷新服务器端文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tls_reflash_Click(object sender, EventArgs e)
        {
            GetRemoteFiles();
        }

        /// <summary>
        /// 右键刷新
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void t_smi_reflash_Click(object sender, EventArgs e)
        {

            GetRemoteFiles();
        }


        /// <summary>
        /// ftp下载回调
        /// </summary>
        /// <param name="i_async_result"></param>
        public void DownloadCallback(IAsyncResult i_async_result)
        {
            try
            {
                m_ftp.EndGetFile(i_async_result);
                if (!IsDisposed)
                    Invoke(new TransferFinishedDelegate(TransferFinished), new object[] { null, false });
            }
            catch (Exception ex)
            {
                WriteToLog(ex.ToString(), Color.Red);
                if (!IsDisposed)
                    Invoke(new TransferFinishedDelegate(TransferFinished), new object[] { ex, false });
            }
        }

     


        /// <summary>
        /// 暂停上传
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tlsm_stop_upload_Click(object sender, EventArgs e)
        {
            if (lst_result_info.SelectedItems.Count <= 0)
            {
                MessageBox.Show("请选择要暂停的上传任务!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            for (int index = 0; index < lst_result_info.SelectedItems.Count; index++)
            {
                string t_file_name = lst_result_info.SelectedItems[index].SubItems[0].Text.Trim();

                UnUploadFileInfo t_file = new UnUploadFileInfo();
                t_file.FileName = t_file_name;
                t_file.UploadSize = m_cur_upload_size;
                lst_result_info.SelectedItems[index].ForeColor = Color.YellowGreen;
                lst_result_info.SelectedItems[index].SubItems[5].Text = "暂停";
                try
                {
                    bool t_ret = LocationManager.AddSettings(t_file);
                    if (t_ret)
                    {
                        m_ftp.Abort();
                        m_is_uploading = false;
                        //SetFtp();
                        //GetRemoteFiles();
                    }
                }
                catch(Exception ex)
                {
                    WriteToLog(ex.Message, Color.Red);
                    SetFtp();
                    GetRemoteFiles();
                }
            }
        }

        /// <summary>
        /// 删除队列
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tlsm_queue_delete_Click(object sender, EventArgs e)
        {
            if (lst_result_info.SelectedItems.Count <= 0)
            {
                MessageBox.Show("请选择要删除的上传任务!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            for (int index = 0; index < lst_result_info.SelectedItems.Count; index++)
            {
                string t_file_name = lst_result_info.SelectedItems[index].SubItems[0].Text.Trim();
                string t_remote_file_name = GetFilenameFromPath(t_file_name);
                lst_result_info.Items.Remove(lst_result_info.SelectedItems[index]);


                try
                {
                    bool t_ret = LocationManager.DelSetting(t_file_name);
                   // if (t_ret)
                   // {
                   //     m_ftp.DeleteFile(t_remote_file_name);

                   //     GetRemoteFiles();

                   //     if (m_is_uploading)
                   //     {
                   //         DoUploadFile();
                   //     }
                   //}
                }
                catch(Exception ex)
                {
                    WriteToLog(ex.Message, Color.Red);

                    SetFtp();

                    GetRemoteFiles();
                }
            }
        }

        /// <summary>
        /// 判断是否有队列
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FrmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            
            if (lst_result_info.Items.Count > 0)
            {
                DialogResult t_dlr = MessageBox.Show("存在没上传完成的文件,确定要退出上传吗?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                if (t_dlr == DialogResult.Yes)
                {
                    UnUploadFileInfo t_file = new UnUploadFileInfo();
                    t_file.FileName = lst_result_info.Items[0].SubItems[0].Text.ToString();
                    t_file.UploadSize = m_cur_upload_size;
                    LocationManager.AddSettings(t_file);
                }
                else
                {
                    e.Cancel = true;
                }
            }
        }

        private void tlsm_file_upload_Click(object sender, EventArgs e)
        {
            //string t_file_path = string.Empty;
            //Monitor.Enter(lst_local_file);
            //for (int index = 0; index < lst_local_file.SelectedItems.Count; index++)
            //{
            //    t_file_path = Path.Combine(tls_cur_path.Text, lst_local_file.SelectedItems[index].Text);

            //    AddUploadFileToList(t_file_path, "0", 0);

            //}
            //Monitor.Exit(lst_local_file);

            if (m_is_uploading == false)
            {
                DoUploadFile();
            }
        }

    }
}
